using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class LinkData
    {
        public object obj;
    }
    public class LinkedListNode
    {
        public int id;
        /// <summary>
        /// 链表内部值
        /// </summary>
        public LinkData Value { get; set; }
        /// <summary>
        /// 指向下一个  internal 内部的
        /// </summary>
        public LinkedListNode Next { get; internal set; }
        /// <summary>
        /// 指向上一个
        /// </summary>
        public LinkedListNode Prev { get; internal set; }
        public LinkedListNode(LinkData value)
        {
            Value = value;
        }
    }
    public class ListedList : IEnumerable
    {
        public LinkedListNode First { get; set; }//第一
        public LinkedListNode Last { get; set; }//最后
        int quantity = 0;

        /// <summary>
        /// 末尾添加
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="node"></param>
        /// <returns></returns>
        public LinkedListNode AddLast(object obj)
        {
            LinkData data = new LinkData();
            data.obj = obj;
            var newNode = new LinkedListNode(data);
            newNode.id = quantity;
            if (First == null)
            {
                First = newNode;

            }
            else
            {
                Last = newNode;
                Last.Next = null;
            }
            quantity++;
            return newNode;
        }
        /// <summary>
        /// 删除末尾节点
        /// </summary>
        /// <returns></returns>
        public LinkedListNode DelLast()
        {
            LinkedListNode delitem = new LinkedListNode(Last.Value);
            Last = Last.Prev;
            quantity--;
            return delitem;
        }


        public LinkedListNode AddPlace(LinkData data)
        {
            LinkedListNode itemLink = First;
            while (itemLink.Next != null)
            {
                if (itemLink.Value == data)
                {
                    LinkedListNode asLink = new LinkedListNode(data);
                    asLink.Prev = itemLink.Prev;
                    asLink.Next = itemLink.Next;
                    itemLink.Prev.Next = asLink;
                    itemLink.Next.Prev = asLink;
                    return itemLink;
                }
                itemLink = itemLink.Next;
            }
            return null;
        }


        public IEnumerator GetEnumerator()
        {
            LinkedListNode current = First;
            while (current != null)
            {
                yield return current.Value;
                current = current.Next;
            }
        }

    }
}
